<template>
  <view class="drag-item" @touchend="handleEnd">
    <image class="drag-img" src="https://app5.shuguostar.cn/imgs/images/demo/bg.png" />

    <movable-area class="drag-content flex flex-col justify-between">
      <view class="content-top flex justify-between">
        <view v-for="(item, index) in question?.questionList" :key="item" class="drag-top">
          <view class="top-question">
            {{ item }}
          </view>
          <view class="top-box">
            {{ answerList?.[index]?.text }}
          </view>
        </view>
      </view>
      <view class="content-bottom flex justify-between">
        <movable-view v-for="(item, index) in question?.answer" :key="`bottom-${item}`" :x="item.x" :y="item.y" direction="all" :animation="false" @change="(e: any) => onChange(e, item, index)">
          <view class="drag-bottom" :class="`drag-bottom-${index}`" :style="{ display: item.show ? 'block' : 'none' }">
            {{ item.text }}
          </view>
        </movable-view>
      </view>
    </movable-area>
  </view>
</template>

<script setup lang="ts" name="DragItem">
import { throttle } from 'uview-plus';
import type { DragQuestion } from '@/pages/views/demo/type';

const props = defineProps({
  question: {
    type: Object as () => DragQuestion,
    default: () => {},
  },
});

const instance = getCurrentInstance() as any;

const answerTextList = ref<Array<string>>([]);
const answerList = ref<Array<{ index: number; text: string }>>([]);
const parentInfo: { left: number; top: number } = { top: 0, left: 0 };
const dragItemInfo: { width: number; height: number } = { width: 0, height: 0 };
let topItemInfo: Array<{ width: number; height: number; x1: number; y1: number; x2: number; y2: number }> = [];

const isRange = (x: number, y: number) => {
  for (let i = 0; i < topItemInfo.length; i++) {
    const item = topItemInfo[i];
    if (item.x1 < x && x < item.x2 && item.y1 < y && y < item.y2) {
      return i;
    }
  }

  return -1;
};

// 记录拖拽信息
const dragItem: { x: number; y: number; item: { text: string; x: number; y: number; oldX: number; oldY: number }; index: number } = { x: 0, y: 0, item: { text: '', x: 0, y: 0, oldX: 0, oldY: 0 }, index: 0 };
const handleData = (e: any, item: { text: string; x: number; y: number; oldX: number; oldY: number }, index: number) => {
  dragItem.x = e.detail.x;
  dragItem.y = e.detail.y;
  dragItem.item = item;
  dragItem.index = index;
};

const onChange = (e: any, item: { text: string; x: number; y: number; oldX: number; oldY: number }, index: number) => {
  throttle(() => handleData(e, item, index), 100, false);
};

// 手指抬起后判断
const handleEnd = () => {
  const flag: number = isRange(dragItem.x + parentInfo.left + dragItemInfo.width / 2, dragItem.y + parentInfo.top + dragItemInfo.height / 2);
  if (flag > -1 && answerList.value[flag]?.text) {
    const answerItem: { text: string; x: number; y: number; oldX: number; oldY: number; show: boolean } = props.question.answer![answerList.value[flag].index];
    answerItem.x = dragItem.x;
    answerItem.y = dragItem.y;
    nextTick(() => {
      answerItem.x = answerItem.oldX;
      answerItem.y = answerItem.oldY;
      answerItem.show = true;
    });

    answerList.value[flag] = { index: dragItem.index, text: dragItem.item.text };
    props.question.answer![dragItem.index].show = false;
  }
  else if (flag > -1 && !answerList.value[flag]?.text) {
    answerList.value[flag] = { index: dragItem.index, text: dragItem.item.text };
    props.question.answer![dragItem.index].show = false;
  }
  else if (flag === -1) {
    const list = answerList.value.filter((item: any) => item.index === dragItem.index);
    if (!list.length) {
      props.question.answer![dragItem.index].x = props.question.answer![dragItem.index].oldX;
      props.question.answer![dragItem.index].y = props.question.answer![dragItem.index].oldY;
    }
  }
};

const isPlay = ref<boolean>(false);
const drag = 'https://app5.shuguostar.cn/imgs/bookVido/audio/drag.mp3';
let innerAudioContext: any;
const playAudio = () => {
  innerAudioContext = uni.createInnerAudioContext();
  innerAudioContext.autoplay = true;
  innerAudioContext.src = drag;
  innerAudioContext.onPlay(() => {
    isPlay.value = true;
  });
  innerAudioContext.onEnded(() => {
    isPlay.value = false;
  });
};

const pauseAudio = () => {
  innerAudioContext?.destroy();
  innerAudioContext = null;
};

onReady(() => {
  playAudio();
  uni.createSelectorQuery().in(instance).selectAll('.top-box').boundingClientRect((rect: any) => {
    topItemInfo = rect.map((item: any) => {
      return {
        width: item.width,
        height: item.height,
        x1: item.left,
        y1: item.top,
        x2: item.left + item.width,
        y2: item.top + item.height,
      };
    });
  }).exec();

  uni.createSelectorQuery().in(instance).select('.drag-item').boundingClientRect((rect: any) => {
    parentInfo.top = rect.top;
    parentInfo.left = rect.left;
  }).exec();

  uni.createSelectorQuery().in(instance).select('.drag-bottom-1').boundingClientRect((rect: any) => {
    dragItemInfo.width = rect.width;
    dragItemInfo.height = rect.height;
  }).exec();
});

watch(() => props.question?.id, () => {
  answerTextList.value = [];
  // answerList.value = [];
}, { deep: true });

defineExpose({
  answerList,
  answerTextList,
  pauseAudio,
});
</script>

<style lang="scss" scoped>
@function tovmin($rpx){//$rpx为需要转换的字号
  @return #{calc($rpx * 100 / 750)}vmin;
}

.drag-item {
  position: relative;
  width: tovmin(1060);
  height: tovmin(540);
  margin: tovmin(40);
  padding: tovmin(10);
  border-radius: tovmin(12);
  background: #fff;

  .drag-img {
    position: absolute;
    top: tovmin(10);
    left: tovmin(10);
    width: tovmin(1040);
    height: tovmin(520);
    border-radius: tovmin(12);
  }

  .drag-content {
    position: relative;
    width: tovmin(1040);
    height: tovmin(520);
    padding: tovmin(30) tovmin(80);
    box-sizing: border-box;

    .content-top {
      padding: tovmin(0) tovmin(55);

      .drag-top {
        width: tovmin(116);
        height: tovmin(127);

        .top-question, .top-box {
          width: tovmin(92);
          height: tovmin(130);
          letter-spacing: tovmin(4);
          text-align: center;
          writing-mode: vertical-rl;
          font-size: tovmin(24);
          line-height: tovmin(92);
          color: #7B4F21;
          background-image: url('https://app5.shuguostar.cn/imgs/images/demo/drag_top_bg.png');
          background-size: 100% 100%;
        }

        .top-question {
          position: relative;
          margin-bottom: tovmin(32);

          &::after {
            content: '';
            position: absolute;
            top: tovmin(130);
            left: tovmin(46);
            width: tovmin(4);
            height: tovmin(32);
            background: #9D6831;
          }
        }
      }
    }

    .content-bottom {
      .drag-bottom {
        width: tovmin(102);
        height: tovmin(73);
        background-image: url('https://app5.shuguostar.cn/imgs/images/demo/drag_bottom_bg.png');
        background-size: 100% 100%;

        font-size: tovmin(20);
        line-height: tovmin(73);
        text-align: center;
        color: #7B4F21;
        font-weight: bold;
      }
    }
  }
}
</style>
